/*
 * NETMAJ - network mahjongg -  Copyright Notice
 *     Copyright (C) 1994, 1995, 1996 Koji Suzuki (suz@kt.rim.or.jp)
 *
 *  You can redistribute it and/or modify this software under the terms 
 * of the GNU General Public License version 2 as published by
 * the Free Software Foundation.
 *
 *  This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the author be held liable for any damages
 * arising from the use of this software.
 * See the gpl.text for more details.
 *
 *  If you would like to do something with NETMAJ that this copyright
 * prohibits (such as distributing it with a commercial product,
 * using portions of the source in some other program, etc.), please
 * contact the author (preferably via email).  Arrangements can
 * probably be worked out.
 *
 *  Koji Suzuki   : suz@kt.rim.or.jp
 */
/* $Id: stand.c,v 1.12 1996/07/31 08:06:26 suz Exp $ */

#include <signal.h>
#include "pai.h"
#include "global.h"

int protocol_version = PROTOCOL_VERSION;
char *msgGets();

talk(gp,from,msg) global_t *gp; char *msg; {
}

runauto(buf) char *buf; {
}

term() {
fprintf(stderr,"term\n");
exit(1);
}

auto_prog(gp,buf) global_t *gp; char *buf;
{
	char msg[256];
	int st,c;
	int res,how;

	st = recv_message(gp,buf);
	switch(st) {
	case ACT_RES:
		res = analize_res(gp,&how);
		sprintf(msg,MSG_REPL,res,how);
		msgWrites(gp,msg,4);
		break;
	case ACT_SEL:
		analize(gp,vself);
		sprintf(msg,MSG_ASK,ask_attr,ask_pai);
		msgWrites(gp,msg,4);
		break;
	case ACT_PEND:
		pf_pend(gp);
		break;
	case ACT_GEND:
		pf_gend(gp);
		pf_term(gp);
		break;
	case ACT_COMMENT:
		break;
	}
}


global_t *globals[5];

FILE *df;
FILE *log_server;

main(argc,argv) int argc; char *argv[]; {
	int i,c,j;
	int dmy;
	char *names[4];

	log_server = stdout;
	srandom(time(0));
#if 0
	df = stderr;
#endif
	for (i=1; i<argc && i<=4; i++) {
		names[i-1] = argv[i];
	}
	for (; i<=4; i++) {
		names[i-1] = "auto";
	}

	for (i=0; i<5; i++) {
		globals[i] = global_alloc();
	}
	for (i=0; i<4; i++) {
		globals[i]->_self = i;
		for (j=0; j<5; j++) {
			strcpy(globals[j]->_player[i].name,names[i]);
			globals[j]->_player[i].flags = 0;
		}
		analize_init(globals[i]);
		pf_init(globals[i],globals[i]->_player[i].name,argv[0]);
	}
	pf_init(globals[4],"server",argv[0]);
	rule_init(globals[4]);
	game(globals[4]);
}

char msgs[4][256];

int msgWrites(gp,buf,p) global_t *gp; char *buf; int p; {
	int i,q = 0;
	if (p==4) {
		for (i = 0; i<4; i++)
			if (gp == globals[i])
				q = i;
		strcpy(msgs[q],buf);
	}
	else {
		auto_prog(globals[p],buf);
	}
}

msgSelect(gp,time_out) global_t *gp; int time_out; {
	return 1;
}

msgIsRead(gp,p) global_t *gp; {
	return (msgs[p][0] != 0);
}

char *msgGets(gp,buf,len,p) global_t *gp; char *buf; int len; int p; {
	if (msgs[p][0]) {
		strcpy(buf,msgs[p]);
		msgs[p][0] = 0;
	}
}
